<?php

class AuthController extends FrontendController
{
    public function actionIndex()
    {
        $this->redirect(Yii::app()->createUrl('user/index'));
    }

    public function actionLogin()
    {
        $user=new User();
        $identity=new DSUserIdentity();

        $user->setScenario('login');
        $this->performAjaxValidation($user);

        if(isset($_POST['User'])){
            $identity->username=$_POST['User']['login'];
            $identity->password=$_POST['User']['password'];

            if($identity->authenticate()){
                Yii::app()->user->setFlash('userMessage','Привет, '.Yii::app()->user->name);
            }else{
                Yii::app()->user->setFlash('userMessage',$identity->errorCode);
                $this->redirect(Yii::app()->createUrl('site/index'));
            }

            if(Yii::app()->user->checkAccess('admin') || Yii::app()->user->checkAccess('moderator')) $this->redirect(Yii::app()->createUrl('admin/index'));
            $this->redirect(Yii::app()->createUrl('user/index'));
        }else{
            $this->render('login',array());
        }
    }

    public function actionSNLogin()
    {
        $this->layout='ext.snauth.views.layouts.SNAuth';

        $user=new User();
        $user->setScenario('SNLogin');
        $this->performAjaxValidation($user);

        Yii::import('user.models.SNUserIdentity');
        $identity=new SNUserIdentity();

        if($identity->SNLogin()){
            Yii::app()->user->setFlash('userMessage','Привет, '.Yii::app()->user->name.'!<br />'.Yii::app()->user->getFlash('userMessage'));
            $identity->close();
        }

        if(Yii::app()->user->getFlash('userMessage')) $identity->close();
        $this->redirect(Yii::app()->createUrl('user/index'));
    }

    public function actionLogout()
    {
        $identity=new DSUserIdentity();
        $identity->logout(User::model()->findByPk(Yii::app()->user->id));


        Yii::app()->user->setFlash('userMessage','Пока, '.Yii::app()->user->name);
        $this->redirect(Yii::app()->createUrl('site/index'));
    }

    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && ($_POST['ajax']==='form-login' || $_POST['ajax']==='form-confirm-email')){
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}